package com.dzm.controller.admin;

import com.dzm.to.LoginUser;
import com.dzm.service.ITokenService;
import com.dzm.service.IUserService;
import com.dzm.utils.JwtUtil;
import com.dzm.utils.R;
import com.dzm.vo.LoginVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 作者：Dzm
 * 时间：2024-08-23-19:41
 * 功能：
 */

@RestController
@RequestMapping("/admin/auth")
public class AuthController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ITokenService tokenService;

    @PostMapping("/login")
    public R login(@RequestBody LoginVo loginVo) {
        LoginUser loginUser = userService.getUserById(loginVo);
        Map<String, Object> map = tokenService.createToken(loginUser);

        return R.ok().data(map);
    }

    @GetMapping("/info")
    public R info(@RequestParam("token")String token) {
        Claims claims = JwtUtil.parseToken(token);
        String username = (String) claims.get("username");

        return R.ok().data("name", username)
                .data("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
    }

    @PostMapping("/logout")
    public R logOut(HttpServletRequest request) {
        tokenService.logout(request);

        return R.ok();
    }
}
